package priv.chenkai.spring_cli.controller;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import priv.chenkai.spring_cli.dao.UserDao;
import priv.chenkai.spring_cli.exception.ReadMessageException;
import priv.chenkai.spring_cli.service.UserService;
import priv.chenkai.spring_cli.util.Pair;
import priv.chenkai.spring_cli.util.Result;
import priv.chenkai.spring_cli.vo.UserVo;

import java.util.List;
import java.util.Optional;

/**
 * 用户控制类
 * Created by chenkai on 2017/11/21.
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 查询用户列表
     * @param start
     * @param size
     * @return
     */
    @GetMapping("/api/users")
    public Result getList(Integer start, Integer size){
        start = Optional.ofNullable(start).orElse(0);
        size = Optional.ofNullable(size).orElse(10);
        Pair<List<UserVo>, Integer> pair = userService.find(start, size);
        return Result.successResult(pair.first,pair.second);
    }

    /**
     * 添加用户
     * @param vo
     * @return
     */
    @PostMapping("/api/users")
    public Result add(@RequestBody UserVo vo){
        userService.insert(vo);
        return Result.successResult();
    }

    /**
     * 更新用户
     * @param vo
     * @return
     */
    @PostMapping("/api/users/{id}")
    public Result update(@PathVariable Integer id, UserVo vo){
        vo.setId(id);
        userService.update(vo);
        return Result.successResult();
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @PostMapping("/api/users/{id}/delete")
    public Result del(@PathVariable Integer id) throws ReadMessageException {
        userService.delete(id);
        return Result.successResult();
    }

    /**
     * 查询用户详情
     * @param id
     * @return
     */
    @GetMapping("/api/users/{id}")
    public Result findById(@PathVariable Integer id){
        UserVo user = userService.findByid(id);
        return Result.successResult(user);
    }
}
